import configparser
import os
import random
import tempfile
import time
import csv
import chardet

from selenium.webdriver.common.by import By
import shutil

userAgents = [
    'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36',
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36'
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36'
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36'
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36'
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 Edg/119.0.0.0',
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
    'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36 SE 2.X MetaSr 1.0',
    'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 UBrowser/6.2.4098.3 Safari/537.36',
    'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36 OPR/81.0.4196.54'
]


def fuzzy_search_folder_by_time(root_folder, keyword):
    folders = [folder for folder in os.listdir(root_folder) if os.path.isdir(os.path.join(root_folder, folder))]
    folders.sort(key=lambda x: os.path.getmtime(os.path.join(root_folder, x)))
    object_path = None
    for folder in folders:
        if keyword in folder:
            object_path = os.path.join(root_folder, folder)
    return object_path


def clear_rust_search_folder_by_time(root_folder, keyword, full_keyword):
    folders = [folder for folder in os.listdir(root_folder) if os.path.isdir(os.path.join(root_folder, folder))]
    folders.sort(key=lambda x: os.path.getmtime(os.path.join(root_folder, x)))
    object_path = None
    for folder in folders:
        if keyword in folder and full_keyword in folder:
            continue
        if keyword in folder:
            shutil.rmtree(f'{root_folder}\{folder}')


def clear_tmp_folder(root_folder, prefix, full_keyword):
    folders = [folder for folder in os.listdir(root_folder) if os.path.isdir(os.path.join(root_folder, folder))]
    folders.sort(key=lambda x: os.path.getmtime(os.path.join(root_folder, x)))
    for folder in folders:
        if full_keyword in folder:
            continue
        if folder.startswith(prefix):
            shutil.rmtree(f'{root_folder}\{folder}')


def ignore_errors(path, exc_info):
    # 忽略特定错误，比如文件正在使用中的错误
    if os.access(path, os.W_OK):
        print(f"Skipping {path} due to error: {exc_info}")
    else:
        raise  # 如果不是特定错误，继续抛出异常


def clear_tmp_and_rust(logger, driver):
    rust_path = fuzzy_search_folder_by_time(tempfile.gettempdir(), 'rust_')
    tmp_path = os.path.dirname(driver.profile.path)
    clear_rust_search_folder_by_time(tempfile.gettempdir(), 'rust_', os.path.basename(rust_path))
    clear_tmp_folder(tempfile.gettempdir(), 'tmp', os.path.basename(tmp_path))


def letter_to_number(letter):
    if letter.isdigit():
        return int(letter)
    elif letter.isalpha():
        ascii_val = ord(letter.upper()) - ord('A')
        return ascii_val % 10
    else:
        return 0


def get_user_agent(did=''):
    userAgent = random.choice(userAgents)
    if did == '':
        return userAgent

    userAgentPath = f'account/{did}/user-agent'
    if os.path.exists(userAgentPath):
        with open(userAgentPath, 'r') as f:
            return f.readline()
    return userAgent


def create_user_agent(did='', userAgent=random.choice(userAgents)):
    userAgentPath = f'account/{did}/user-agent'
    with open(userAgentPath, 'w') as f:
        f.write(userAgent)


csv_encoding = ''
def read_specific_line(filename, line_number):
    # 读取文件并检测编码
    global csv_encoding
    if csv_encoding == '':
        with open(filename, 'rb') as file:
            rawdata = file.read()
            result = chardet.detect(rawdata)
            csv_encoding = result['encoding']

    # 使用检测到的编码来读取文件
    with open(filename, 'r', encoding=csv_encoding) as file:
        reader = csv.reader(file)
        for i, line in enumerate(reader):
            if i == line_number:
                return line
    return ''


def read_column(filename, column_index):
    result = []
    if os.path.exists(filename):
        with open(filename, 'r') as file:
            reader = csv.reader(file)
            for i, row in enumerate(reader, start=1):
                if len(row) > 0:
                    result.append(row[column_index])
    return result


# get_comment_index_and_gailv('account/199362197/comment.csv')
def get_one_comment_by_weight(filename1, filename2):
    # 读取文件并检测编码
    probs1 = read_column(filename1, 1)
    probs2 = read_column(filename2, 1)
    probs = probs1 + probs2
    if len(probs) == 0:
        return ''
    probs = [float(x) for x in probs]

    selected_element = random.choices(list(range(len(probs))), weights=probs)[0]
    if selected_element < len(probs1):
        line = read_specific_line(filename1, selected_element)
    else:
        line = read_specific_line(filename2, selected_element - len(probs1))
    return line[0]


class ConfigChecker:
    def __init__(self, config_file, default_config_file):
        self.config = configparser.ConfigParser()
        self.config.read(config_file, encoding='utf-8')
        self.default_config_file = configparser.ConfigParser()
        self.default_config_file.read(default_config_file, encoding='utf-8')

    def check_field(self, section, field):
        if section in self.config and field in self.config[section]:
            return True, self.config[section][field]
        elif section in self.default_config_file and field in self.default_config_file[section]:
            return False, self.default_config_file[section][field]
        else:
            return False, None

    def check_fields(self, fields):
        for section, field in fields:
            if section in self.config and field in self.config[section]:
                return True, self.config[section][field]
            elif section in self.default_config_file and field in self.default_config_file[section]:
                return False, self.default_config_file[section][field]
            else:
                return False, None



